package com.lcx.db137.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lcx.db137.common.R;
import com.lcx.db137.entity.Menu;
import com.lcx.db137.entity.Rolemenu;
import com.lcx.db137.entity.User;
import com.lcx.db137.service.MenuService;
import com.lcx.db137.service.RolemenuService;
import com.lcx.db137.service.UserService;
import com.lcx.db137.service.impl.MenuServiceImpl;
import com.lcx.db137.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * (menu)表控制层
 *
 * @author xxxxx
 */
@RestController
@CrossOrigin(origins = "*")
public class MenuController {
    /**
     * 服务对象
     */
    @Autowired
    private MenuService menuService;
    @Autowired
    private RolemenuService rolemenuService;
    @Autowired
    private UserService userService;

    //查询用户菜单
    @GetMapping("/selectusermenu")
    public R selectMenuByUserId(@RequestHeader("token")String token) {
        //解析token，获取用户id
        Integer userId = JwtUtils.getJwtToken(token, "userid");
        System.out.println(userId);
        //通过id查询用户信息
        User user =  userService.getById(userId);
        System.out.println("user = " + user);
        List<Menu> menus = menuService.selectMenuByUserId(userId);
        return new R().add("menus", menus).add("user", user);
    }

    //查询所有菜单
    @GetMapping("/selectallmenu")
    public R selectAllMenu(String menuname) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if (!menuname.equals("undefined")) {
            queryWrapper.like("label", menuname);
        }
        List<Menu> menus = menuService.list(queryWrapper);
        return new R().add("menus", menus);
    }

    //删除
    @PostMapping("/deletemenu")
    public R deleteMenu(Integer id) {
        boolean b = menuService.removeById(id);
        return new R().add("b", b);
    }

    //添加
    @PostMapping("/addmenu")
    public R addMenu(@RequestBody Menu menu) {
        boolean b = menuService.save(menu);
        if (b) {
            QueryWrapper queryWrapper = new QueryWrapper<>();
            //查询id最大值
            queryWrapper.select("max(id) id");
            Menu one = menuService.getOne(queryWrapper);
            System.out.println("one = " + one.getId());
            rolemenuService.save(new Rolemenu(0, 1, one.getId()));
        }
        return new R().add("b", b);
    }

    //修改
    @PostMapping("/updatemenu")
    public R updateMenu(@RequestBody Menu menu) {
        boolean b = menuService.updateById(menu);
        return new R().add("b", b);
    }

    //根据id查询菜单
    @GetMapping("/selectmenuId")
    public R selectMenu(Integer id) {
        Menu menu = menuService.getById(id);
        return new R().add("menu", menu);
    }
}
